using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using eShop.Utility;


namespace Entity
{
	/// <summary>
	/// This object represents the Private Fields of TblInventory.
	/// </summary>
	
	[System.ComponentModel.DataObject]
    public class TblInventory : DatabaseUtility
    {
		#region TblInventory Private Fields


		Int32 _inventoryId;
		Int32 _productId;
		String _productName = String.Empty;
		String _itemNumber = String.Empty;
		Decimal _price;
		Int32 _qTY;
		Decimal _costValue;
		
		#endregion
		#region TblInventory Constractor
		/// <summary>
        /// Creates an empty object of TblInventory. 
        /// This is mainly used to create a new instance of TblInventory to add a new TblInventory.
        /// </summary>
		public TblInventory(){}
		
				
		/// <summary>
        /// Used to retrieve employee information from database, 
        /// which is also used by Update method to save information of an existing TblInventory.
        /// </summary>
		public TblInventory
		(
			Int32 inventoryId,
			Int32 productId,
			String productName,
			String itemNumber,
			Decimal price,
			Int32 qTY,
			Decimal costValue
		)
		{
			_inventoryId = inventoryId;	
			_productId = productId;	
			_productName = productName;	
			_itemNumber = itemNumber;	
			_price = price;	
			_qTY = qTY;	
			_costValue = costValue;	
		}
		
		#endregion
		#region TblInventory Properties
		
		 /***********************************************************************************************
                                    -- PROPERTIES --        
         Contains all the properties representing the data fields of the current entity.
         ***********************************************************************************************/

        /// <summary>
        /// This is the Primary key value of the InventoryId, which can't be assigned from the application,
        /// to ensure the data consistancy, by not letting the user to change the PK_TblInventory to update the data of an another TblInventory instance.
        /// For view or updation purpose, every TblInventory will be retrieved thru the proper 'Get' method.
        /// </summary>
		
		public Int32 InventoryId
		{
			get {return _inventoryId;}	
		}
		
				
		public Int32 ProductId
		{
			get {return _productId;}
			set {_productId = value;}
		}

		public String ProductName
		{
			get {return _productName;}
			set {_productName = value;}
		}

		public String ItemNumber
		{
			get {return _itemNumber;}
			set {_itemNumber = value;}
		}

		public Decimal Price
		{
			get {return _price;}
			set {_price = value;}
		}

		public Int32 QTY
		{
			get {return _qTY;}
			set {_qTY = value;}
		}

		public Decimal CostValue
		{
			get {return _costValue;}
			set {_costValue = value;}
		}
		

		#endregion
		#region TblInventory Static Methods
		/************************************************************************************
                                    -- CREATE METHOD (STATIC) --
        *************************************************************************************/
		/************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
        public static  Int32 CreateNewTblInventory
		(
			Int32 productId,
			String productName,
			String itemNumber,
			Decimal price,
			Int32 qTY,
			Decimal costValue
		)
		{
			//creating an empty TblInventory object
            TblInventory tblInventory = new TblInventory();
				tblInventory.ProductId = productId;
				tblInventory.ProductName = productName;
				tblInventory.ItemNumber = itemNumber;
				tblInventory.Price = price;
				tblInventory.QTY = qTY;
				tblInventory.CostValue = costValue;
			
			return TblInventory.CreateNewTblInventory(tblInventory);
		}
	
		/************************************************************************************
                 -- UPDATE METHODS (STATIC) --
        *************************************************************************************/

        /************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        There the two types of paramaters will be passed here.
         * a. Primary key paramater: it should be Sql type, as we will bind the primary key property for the view controls (form view, details view etc) as datakey.
         * b. Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static  bool UpdateTblInventory
		(
			Int32 inventoryId,
			Int32 productId,
			String productName,
			String itemNumber,
			Decimal price,
			Int32 qTY,
			Decimal costValue
		)
		{
			 TblInventory tblInventory =  TblInventory.GetTblInventoryByInventoryId(inventoryId);
			
				tblInventory.ProductId = productId;
				tblInventory.ProductName = productName;
				tblInventory.ItemNumber = itemNumber;
				tblInventory.Price = price;
				tblInventory.QTY = qTY;
				tblInventory.CostValue = costValue;
			
			return TblInventory.UpdateTblInventory(tblInventory);
		}

		/************************************************************************************
                         -- DELETE METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        ****************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static  bool DeleteTblInventory
		(
			Int32 inventoryId
		)
		{
			//Validate Input
			if(inventoryId <= GetInventoryIdMinValue)
				throw (new ArgumentOutOfRangeException("inventoryId"));
				
			// Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
			AddParameterToSqlCmd(sqlCmd, "@InventoryId",SqlDbType.Int, 0, ParameterDirection.Input, inventoryId);
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_DELETETBLINVENTORY);
			ExecuteScalarCmd(sqlCmd);
			int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
			return (returnValue == 0 ? false : true);
			
		}
		
		/// <summary>
        /// Deletes a set of employees from the database.
        /// </summary>
		public static bool DeleteTblInventoryList( System.Collections.Generic.List<Int32>  inventoryIdListToDelete)
		{
			//Validate Input
			foreach (Int32 inventoryId in inventoryIdListToDelete)
			    if(inventoryId <= GetInventoryIdMinValue)
					throw (new ArgumentOutOfRangeException("inventoryId"));
			
			//performing deletion operation //

            string xmlString = FormatXMLForIdArray(inventoryIdListToDelete);
			
			// Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@InventoryIdList", SqlDbType.Xml, xmlString.ToString().Length, ParameterDirection.Input, xmlString.ToString());
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_DELETETBLINVENTORYLIST);
			ExecuteScalarCmd(sqlCmd);
			int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
			return (returnValue == inventoryIdListToDelete.Count ? true : false);
		}
		
		/************************************************************************************
                                 -- GET BY PRIMARY METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        Retrives an Employee from database, based on it's primary key.
        To view or update an employee, everytime we must have to use this type of 'get' method, 
        since we don't have direct access to the Primary key value for assigning value.
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        /*****************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
		public static TblInventory GetTblInventoryByInventoryId(Int32 inventoryId)
		{
			if(inventoryId <= GetInventoryIdMinValue)
					throw (new ArgumentOutOfRangeException("inventoryId"));
				
		 	// Execute SQL Command
			SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@InventoryId",SqlDbType.Int, 0, ParameterDirection.Input, inventoryId);
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_GETTBLINVENTORYBYINVENTORYID);
			GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblInventoryCollectionFromReader);
            List<TblInventory> objCollection = ((List<TblInventory>)ExecuteReaderCmd(sqlCmd, test));

            if (objCollection.Count > 0)
                return objCollection[0];
            else
                return null;
		}
		
		/************************************************************************************
                         -- GET BY FOREIGN KEY METHODS --
        *************************************************************************************/
		
		/************************************************************************************
                 -- GET ALL METHODS --
        *************************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static List<TblInventory> GetAllTblInventory()
		{
		
		 	// Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_GETALLTBLINVENTORY);
            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblInventoryCollectionFromReader);
            List<TblInventory> objCollection = ((List<TblInventory>)ExecuteReaderCmd(sqlCmd, test));

            return objCollection;
		}
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static List<TblInventory> GetAllTblInventoryPaged(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            //Validate Input
            if (orderBy == "")
                orderBy = "InventoryId";

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@orderby", SqlDbType.VarChar, 50, ParameterDirection.Input, orderBy);
            AddParameterToSqlCmd(sqlCmd, "@startrow", SqlDbType.Int, 0, ParameterDirection.Input, startRowIndex);
            AddParameterToSqlCmd(sqlCmd, "@pagesize", SqlDbType.Int, 0, ParameterDirection.Input, maximumRows);

            SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_GETALLTBLINVENTORYPAGED);

            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblInventoryCollectionFromReader);
            List<TblInventory> objCollection = ((List<TblInventory>)ExecuteReaderCmd(sqlCmd, test));
            return objCollection;
        }
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static int GetAllTblInventoryPagedCount(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();

            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_GETALLTBLINVENTORYPAGEDCOUNT);
            ExecuteScalarCmd(sqlCmd);

            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return returnValue;
        }
		
		#endregion
		#region Employee Instance Methods
		/************************************************************************************
                                    -- SAVE (INSERT/UPDATE) METHODS (INSTANCE) --
        *************************************************************************************/
		/// <summary>
        /// Saves (inserts and updates) an Employee into database.
        /// The insertion occur if the EmployeeId conatins default value.
        /// Otherwises it updates the Employee into the database, based on the primary key value stored in EmployeeId.
        /// This technique ensures an Employee will not be updated without having a valid EmployeeId.
        /// </summary>
		public bool Save()
		{
			if(InventoryId<= GetInventoryIdMinValue)
			{
				Int32 TempId=CreateNewTblInventory(this);
				if(TempId>0)
				{
					_inventoryId=TempId;
					return true;
				}
				else
				{
					// error occurs
					return false;
				}
			}
			else
			{	//This is a update Command
				return (UpdateTblInventory(this));
			}
			
		}
		
		public static Int32 CreateNewTblInventory(TblInventory newTblInventory)
		{
			// validate Parameters
			if (newTblInventory == null)
				throw (new ArgumentNullException("newTblInventory"));

			// Execute SQL Command
			SqlCommand sqlCmd = new SqlCommand();
			int length = 0;
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            
			AddParameterToSqlCmd(sqlCmd, "@ProductId",SqlDbType.Int, 0, ParameterDirection.Input, newTblInventory.ProductId);
			AddParameterToSqlCmd(sqlCmd, "@ProductName",SqlDbType.VarChar, 500, ParameterDirection.Input, newTblInventory.ProductName);
			AddParameterToSqlCmd(sqlCmd, "@ItemNumber",SqlDbType.VarChar, 50, ParameterDirection.Input, newTblInventory.ItemNumber);
			AddParameterToSqlCmd(sqlCmd, "@Price",SqlDbType.Decimal, 9, ParameterDirection.Input, newTblInventory.Price);
			AddParameterToSqlCmd(sqlCmd, "@QTY",SqlDbType.Int, 0, ParameterDirection.Input, newTblInventory.QTY);
			AddParameterToSqlCmd(sqlCmd, "@CostValue",SqlDbType.Decimal, 9, ParameterDirection.Input, newTblInventory.CostValue);
			
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_CREATENEWTBLINVENTORY);
			ExecuteScalarCmd(sqlCmd);
			return (Int32.Parse(sqlCmd.Parameters["@ReturnValue"].Value.ToString()));

		}
		/// <summary>
        /// Updates an TblInventory instance to the database.
        /// </summary>
		public static bool UpdateTblInventory(TblInventory newTblInventory)
		{
			// validate Parameters
			if (newTblInventory == null)
				throw (new ArgumentNullException("newTblInventory"));

			// Execute SQL Command
			SqlCommand sqlCmd = new SqlCommand();
			int length = 0;
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            
			AddParameterToSqlCmd(sqlCmd, "@InventoryId",SqlDbType.Int, 0, ParameterDirection.Input, newTblInventory.InventoryId);
			AddParameterToSqlCmd(sqlCmd, "@ProductId",SqlDbType.Int, 0, ParameterDirection.Input, newTblInventory.ProductId);
			AddParameterToSqlCmd(sqlCmd, "@ProductName",SqlDbType.VarChar, 500, ParameterDirection.Input, newTblInventory.ProductName);
			AddParameterToSqlCmd(sqlCmd, "@ItemNumber",SqlDbType.VarChar, 50, ParameterDirection.Input, newTblInventory.ItemNumber);
			AddParameterToSqlCmd(sqlCmd, "@Price",SqlDbType.Decimal, 9, ParameterDirection.Input, newTblInventory.Price);
			AddParameterToSqlCmd(sqlCmd, "@QTY",SqlDbType.Int, 0, ParameterDirection.Input, newTblInventory.QTY);
			AddParameterToSqlCmd(sqlCmd, "@CostValue",SqlDbType.Decimal, 9, ParameterDirection.Input, newTblInventory.CostValue);
			
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLINVENTORY_UPDATETBLINVENTORY);
            ExecuteScalarCmd(sqlCmd);
			int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
			return (returnValue == 0 ? false : true);
		}
		#endregion
		
		#region TblInventory Related Collections
		/// <summary>
        /// Creates and returns a strongly typed collection of Employee custom entity. 
        /// The colelction is created through iterating on the IdataReader object which contains Employee information, as a set of records, similar to tabular format.
        /// </summary>
		public static IList  GenerateTblInventoryCollectionFromReader(IDataReader returnData) 
		{
			
			//creating the instance of Employee collection
			List<TblInventory> colTblInventory = new List<TblInventory>();
			
			/************************* Architecure note:**********************************
             * Below code includes the null value functionality to retieve the data which has nill value in database end.
             * Design consideration:
             * Besides general data fields, special care should be taken for primary keys, to assign '0'/defaultvalue, rather passing 'Null' value in constructor parameter.
             * Although we are considering sqldb tyoe data for the current data container, but while retireving data from database end, through datareader object, we need to cast data reader objects using .net primitive data type, 
             * rather using sqldb type to cast, since data reader objects don't support sql db type to be casted.
             *****************************************************************************/

            //Iterating thriugh the data reader, to generate Employee collection.

			//getting the Employee collection by iterating thru the data reader
			while (returnData.Read()) 
			{
				//passing the TblInventory constructor parameters from the current instance of data reader fields.
				TblInventory newTblInventory = new TblInventory
				(
					returnData["InventoryId"]== System.DBNull.Value ? GetInventoryIdMinValue : (Int32 ) returnData["InventoryId"],
					returnData["ProductId"]== System.DBNull.Value ? 0: (Int32 ) returnData["ProductId"],
					returnData["ProductName"]== System.DBNull.Value ? string.Empty: (String ) returnData["ProductName"],
					returnData["ItemNumber"]== System.DBNull.Value ? string.Empty: (String ) returnData["ItemNumber"],
					returnData["Price"]== System.DBNull.Value ? 0: (Decimal ) returnData["Price"],
					returnData["QTY"]== System.DBNull.Value ? 0: (Int32 ) returnData["QTY"],
					returnData["CostValue"]== System.DBNull.Value ? 0: (Decimal ) returnData["CostValue"]

				);
				//adding the Employee to the collection
				colTblInventory.Add(newTblInventory);
			}
			
			//returns the collection of Companys 
			return (colTblInventory);
		}
		
		#endregion
		#region Constants and Default Values
		
		public static Int32 GetInventoryIdMinValue
		{
			get
			{
				return 0;
			}
		}
		
		//create method related contants
			internal const string SPR_TBLINVENTORY_CREATENEWTBLINVENTORY="spr_TblInventory_CreateNewTblInventory";
			internal const string SPR_TBLINVENTORY_UPDATETBLINVENTORY="spr_TblInventory_UpdateTblInventory";
			internal const string SPR_TBLINVENTORY_DELETETBLINVENTORY="spr_TblInventory_DeleteTblInventory";
			internal const string SPR_TBLINVENTORY_DELETETBLINVENTORYLIST="spr_TblInventory_DeleteTblInventoryList";
			internal const string SPR_TBLINVENTORY_GETTBLINVENTORYBYINVENTORYID="spr_TblInventory_GetTblInventoryByInventoryId";
			internal const string SPR_TBLINVENTORY_GETALLTBLINVENTORY="spr_TblInventory_GetAllTblInventory";
			internal const string SPR_TBLINVENTORY_GETALLTBLINVENTORYPAGED="spr_TblInventory_GetAllTblInventoryPaged";
			internal const string SPR_TBLINVENTORY_GETALLTBLINVENTORYPAGEDCOUNT="spr_TblInventory_GetAllTblInventoryPagedCount";
		
		#endregion
	}
}	
